package cn.learn.activiti.service.impl;

import cn.learn.activiti.service.IDeploymentService;
import lombok.RequiredArgsConstructor;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 发布流程
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年03月11日15:37
 */
@RequiredArgsConstructor
@Service
public class DeploymentServiceImpl implements IDeploymentService {

    private final RepositoryService repositoryService;

    @Override
    public Deployment deploy(String bpmn, String name) {
        //判断名称格式
        Assert.isTrue(name.lastIndexOf(".bpmn") > 0, "文件名称格式不对！");
        Deployment deploy = repositoryService.createDeployment()
                //name test1.bpmn
                .addString(name, bpmn)
                .deploy();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .latestVersion()
                .singleResult();
        System.out.println(processDefinition);

        return deploy;
    }

    @Override
    public ProcessDefinition getProcessDefinitionById(String getProcessDefinitionId) {
        return repositoryService.createProcessDefinitionQuery().processDefinitionId(getProcessDefinitionId).singleResult();
    }

    @Override
    public InputStream getResource(String deploymentId, String resourceName) {
        return repositoryService.getResourceAsStream(deploymentId, resourceName);
    }

    @Override
    public InputStream getResource(String processDefinitionId) {
        ProcessDefinition processDefinition = this.getProcessDefinitionById(processDefinitionId);
        return this.getResource(processDefinition.getDeploymentId(), processDefinition.getResourceName());
    }

    @Override
    public BpmnModel getBpmnModel(String processDefinitionId) {
        return repositoryService.getBpmnModel(processDefinitionId);
    }

    /**
     * 获取指定节点的上一个节点
     *
     * @param flowNode 指定节点
     * @return 返回结果
     */
    public List<FlowElement> getPreFlowElements(FlowNode flowNode) {
        List<FlowElement>  flowNodes     = new ArrayList<>();
        List<SequenceFlow> incomingFlows = flowNode.getIncomingFlows();
        for (SequenceFlow incomingFlow : incomingFlows) {
            FlowElement element = incomingFlow.getTargetFlowElement();
            flowNodes.add(element);
        }
        return flowNodes;
    }


}
